package com.example.testapp.ui.mine

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.example.testapp.R
import com.example.testapp.config.ApiProviderManager
import com.example.testapp.databinding.ActivityApiConfigBinding

/**
 * API配置页面 - iOS风格
 */
class ApiConfigActivity : AppCompatActivity() {

    // 视图绑定
    private lateinit var binding: ActivityApiConfigBinding
    
    // 配置参数
    private var title: String? = null
    private var isImageApi: Boolean = true
    private var preloadedProvider: String = ""
    private var preloadedUrl: String = ""
    private var preloadedKey: String = ""
    
    // 当前选中的服务提供商
    private var selectedProvider: String = ""
    
    // 保存的配置值
    private var savedProvider: String = ""
    private var savedApiUrl: String = ""
    private var savedApiKey: String = ""
    
    companion object {
        // 意图键
        const val EXTRA_TITLE = "extra_title"
        const val EXTRA_IS_IMAGE_API = "extra_is_image_api"
        const val EXTRA_PROVIDER = "extra_provider"
        const val EXTRA_API_URL = "extra_api_url"
        const val EXTRA_API_KEY = "extra_api_key"
        
        // 返回结果键
        const val RESULT_PROVIDER = "result_provider"
        const val RESULT_API_URL = "result_api_url"
        const val RESULT_API_KEY = "result_api_key"
        
        /**
         * 启动API配置活动的静态方法
         */
        fun newIntent(context: Context, title: String, isImageApi: Boolean,
                      provider: String?, url: String?, key: String?): Intent {
            val intent = Intent(context, ApiConfigActivity::class.java)
            intent.putExtra(EXTRA_TITLE, title)
            intent.putExtra(EXTRA_IS_IMAGE_API, isImageApi)
            intent.putExtra(EXTRA_PROVIDER, provider)
            intent.putExtra(EXTRA_API_URL, url)
            intent.putExtra(EXTRA_API_KEY, key)
            return intent
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化视图绑定 - 移到前面
        binding = ActivityApiConfigBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 设置状态栏颜色与标题栏一致 - 在setContentView之后设置
        window.statusBarColor = androidx.core.content.ContextCompat.getColor(this, R.color.card_blue)
        
        // 使用WindowInsetsControllerCompat设置状态栏文字颜色为白色（适用于深色背景）
        // 这是一个兼容性API，可以在所有Android版本上工作，避免使用过时的API
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        // 设置状态栏文字和图标为白色
        windowInsetsController.isAppearanceLightStatusBars = false
        
        // 确保状态栏正确显示
        WindowCompat.setDecorFitsSystemWindows(window, true)
        
        // 处理Intent中的参数
        handleIntent()
        
        // 设置iOS风格标题栏
        setupTitleBar()
        
        // 初始化视图
        initViews()
        
        // 设置监听器
        setupListeners()
    }
    
    /**
     * 处理Intent中的参数
     */
    private fun handleIntent() {
        intent?.let {
            title = it.getStringExtra(EXTRA_TITLE)
            isImageApi = it.getBooleanExtra(EXTRA_IS_IMAGE_API, true)
            it.getStringExtra(EXTRA_PROVIDER)?.let { provider ->
                preloadedProvider = provider
                if (provider.isNotEmpty()) {
                    selectedProvider = provider
                    savedProvider = provider
                }
            }
            
            // 初始化已保存的值
            it.getStringExtra(EXTRA_API_URL)?.let { url ->
                if (url.isNotEmpty()) {
                    preloadedUrl = url
                    savedApiUrl = url
                }
            }
            
            it.getStringExtra(EXTRA_API_KEY)?.let { key ->
                if (key.isNotEmpty()) {
                    preloadedKey = key
                    savedApiKey = key
                }
            }
        }
    }
    
    /**
     * 设置iOS风格标题栏
     */
    private fun setupTitleBar() {
        // 设置标题
        val tvTitle = binding.tvTitle
        if (!title.isNullOrEmpty()) {
            tvTitle.text = title
        } else {
            tvTitle.text = if (isImageApi) "图片识别API配置" else "AI API配置"
        }
        
        // 设置返回按钮
        val btnBack = binding.btnBack
        btnBack.setOnClickListener { onBackPressed() }
    }
    
    /**
     * 初始化视图
     */
    private fun initViews() {
        // 预加载数据
        preloadConfig()
    }
    
    /**
     * 预加载配置数据到UI
     */
    private fun preloadConfig() {
        try {
            if (preloadedProvider.isNotEmpty()) {
                binding.etServiceProvider.setText(selectedProvider)
                
                // 根据是否是预设提供商设置URL编辑状态
                if (ApiProviderManager.isPresetProvider(preloadedProvider)) {
                    binding.etApiUrl.isEnabled = false
                    binding.etApiUrl.setTextColor(androidx.core.content.ContextCompat.getColor(this, android.R.color.darker_gray))
                    binding.etApiUrl.hint = "预设API地址 (不可编辑)"
                } else {
                    binding.etApiUrl.isEnabled = true
                    binding.etApiUrl.setTextColor(androidx.core.content.ContextCompat.getColor(this, android.R.color.black))
                    binding.etApiUrl.hint = "请输入API地址"
                }
            }
            
            if (preloadedUrl.isNotEmpty()) {
                binding.etApiUrl.setText(preloadedUrl)
            }
            
            if (preloadedKey.isNotEmpty()) {
                // 对API Key进行掩码处理，显示一头一尾，中间用星号代替
                binding.etApiKey.setText(maskApiKey(preloadedKey))
                binding.etApiKey.tag = preloadedKey // 保存原始值到Tag中
            }
        } catch (e: Exception) {
            Toast.makeText(this, "加载配置失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
    
    /**
     * 设置监听器
     */
    private fun setupListeners() {
        // 服务提供商选择 - 使用整个布局作为点击区域
        binding.layoutServiceProvider.setOnClickListener { showProviderPicker() }
        
        // 保存按钮点击
        binding.btnSave.setOnClickListener { saveConfig() }
        
        // 返回按钮的额外处理 - 如果有更改，先保存结果
        binding.btnBack.setOnClickListener {
            handleBackWithSavedChanges()
        }
        
        // API Key编辑框获取焦点时，显示完整值
        binding.etApiKey.setOnFocusChangeListener { v, hasFocus ->
            val etApiKey = v as EditText
            val originalKey = etApiKey.tag
            
            if (hasFocus && originalKey != null) {
                // 获取焦点时显示完整API Key
                etApiKey.setText(originalKey.toString())
            } else if (!hasFocus && originalKey != null) {
                val currentText = etApiKey.text.toString().trim()
                if (currentText != originalKey.toString()) {
                    // 如果值已更改，更新原始值
                    etApiKey.tag = currentText
                }
                // 失去焦点时显示掩码
                etApiKey.setText(maskApiKey(currentText))
            }
        }
    }
    
    /**
     * 显示底部弹出的提供商选择器
     */
    private fun showProviderPicker() {
        try {
            // 获取提供商列表
            val providers = if (isImageApi)
                ApiProviderManager.getImageApiProviders()
            else
                ApiProviderManager.getAiApiProviders()
            
            // 创建并显示底部弹出选择器
            val pickerDialog = ProviderPickerDialog(
                this, 
                providers, 
                "选择服务提供商"
            )
            
            // 预选中当前值
            if (selectedProvider.isNotEmpty()) {
                pickerDialog.preSelectProvider(selectedProvider)
            }
            
            // 设置选择监听器
            pickerDialog.setOnProviderSelectedListener { provider, apiUrl ->
                selectedProvider = provider
                binding.etServiceProvider.setText(provider)
                
                // 如果提供了API地址，自动填充
                if (!apiUrl.isNullOrEmpty()) {
                    binding.etApiUrl.setText(apiUrl)
                    
                    // 如果是预设提供商，禁用编辑
                    if (ApiProviderManager.isPresetProvider(provider)) {
                        binding.etApiUrl.isEnabled = false
                        binding.etApiUrl.setTextColor(androidx.core.content.ContextCompat.getColor(this, android.R.color.darker_gray))
                        binding.etApiUrl.hint = "预设API地址 (不可编辑)"
                    } else {
                        binding.etApiUrl.isEnabled = true
                        binding.etApiUrl.setTextColor(androidx.core.content.ContextCompat.getColor(this, android.R.color.black))
                        binding.etApiUrl.hint = "请输入API地址"
                    }
                } else {
                    // 处理没有API地址的情况
                    handleProviderSelection(provider)
                }
            }
            
            // 显示选择器
            pickerDialog.show()
        } catch (e: Exception) {
            Toast.makeText(this, "加载服务提供商失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
    
    /**
     * 处理服务提供商选择
     */
    private fun handleProviderSelection(provider: String) {
        // 从预设列表中选择时，自动填充API URL
        val apiUrl = ApiProviderManager.getApiUrl(provider)
        if (!apiUrl.isNullOrEmpty()) {
            binding.etApiUrl.setText(apiUrl)
            binding.etApiUrl.isEnabled = false  // 预设URL不允许编辑
            binding.etApiUrl.setTextColor(androidx.core.content.ContextCompat.getColor(this, android.R.color.darker_gray))
            binding.etApiUrl.hint = "预设API地址 (不可编辑)"
        }
    }
    
    /**
     * 保存配置并显示成功提示，不退出页面
     */
    private fun saveConfig() {
        try {
            // 获取输入值
            val provider = selectedProvider
            val apiUrl = binding.etApiUrl.text.toString().trim()
            
            // 获取API Key - 检查是否有原始值
            val apiKey: String
            val originalKey = binding.etApiKey.tag
            val displayedKey = binding.etApiKey.text.toString().trim()
            
            // 如果显示的是掩码且存在原始值，使用原始值
            apiKey = if (originalKey != null && displayedKey.contains("*")) {
                originalKey.toString()
            } else {
                // 否则使用输入框中的值
                displayedKey
            }
            
            // 验证输入
            if (provider.isEmpty()) {
                Toast.makeText(this, "请选择服务提供商", Toast.LENGTH_SHORT).show()
                return
            }
            
            // 预设提供商但URL为空时，自动获取URL
            var finalApiUrl = apiUrl
            if (ApiProviderManager.isPresetProvider(provider) && finalApiUrl.isEmpty()) {
                ApiProviderManager.getApiUrl(provider)?.let {
                    finalApiUrl = it
                }
            }
            
            // 保存到结果变量
            savedProvider = provider
            savedApiUrl = finalApiUrl
            savedApiKey = apiKey
            
            // 显示保存成功提示，不退出页面
            Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show()
            
            // 显示绿色成功提示文本
            binding.tvSaveSuccess.visibility = View.VISIBLE
            
            // 3秒后隐藏提示文本
            binding.tvSaveSuccess.postDelayed({
                if (!isFinishing && binding.tvSaveSuccess != null) {
                    binding.tvSaveSuccess.visibility = View.GONE
                }
            }, 3000)
            
            // 创建并保存结果意图，在返回时使用
            prepareResultIntent()
            
            // 更新显示为掩码形式
            binding.etApiKey.setText(maskApiKey(apiKey))
            binding.etApiKey.tag = apiKey
            
        } catch (e: Exception) {
            Toast.makeText(this, "保存配置失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }
    
    /**
     * 准备结果意图
     */
    private fun prepareResultIntent(): Intent {
        val resultIntent = Intent()
        resultIntent.putExtra(RESULT_PROVIDER, savedProvider)
        resultIntent.putExtra(RESULT_API_URL, savedApiUrl)
        resultIntent.putExtra(RESULT_API_KEY, savedApiKey)
        
        // 设置结果，但不结束Activity
        setResult(Activity.RESULT_OK, resultIntent)
        
        return resultIntent
    }
    
    /**
     * 处理返回动作 - 如果有更改，返回保存的结果
     */
    private fun handleBackWithSavedChanges() {
        // 检查是否有已保存的更改
        if (savedProvider.isNotEmpty()) {
            // 再次确保结果意图已设置
            prepareResultIntent()
        }
        
        // 正常退出
        onBackPressed()
    }
    
    override fun onBackPressed() {
        super.onBackPressed()
        // 添加iOS风格的滑动返回动画
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
    }
    
    /**
     * 对API Key进行掩码处理，显示首尾字符，中间用星号代替
     */
    private fun maskApiKey(apiKey: String?): String {
        if (apiKey.isNullOrEmpty()) {
            return ""
        }
        
        val length = apiKey.length
        
        // 如果长度小于等于6，显示第一个和最后一个字符，其余用星号代替
        if (length <= 6) {
            if (length <= 1) {
                return apiKey // 如果只有一个字符，不做掩码
            }
            return apiKey[0] + "*****" + apiKey[length - 1]
        }
        
        // 长度大于6的情况，显示首尾各25%的字符，中间用星号代替
        val visibleChars = maxOf(1, length / 4) // 至少显示1个字符
        
        val firstPart = apiKey.substring(0, visibleChars)
        val lastPart = apiKey.substring(length - visibleChars)
        
        val masked = StringBuilder(firstPart)
        
        // 添加星号，星号数量为总长度减去首尾显示的字符数，但不少于5个
        val stars = maxOf(5, length - (2 * visibleChars))
        for (i in 0 until stars) {
            masked.append("*")
        }
        
        masked.append(lastPart)
        
        return masked.toString()
    }
}